package com.weedsdream.app.struct

import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.weedsdream.app.colorplate.ColorSetData
import com.weedsdream.function.inCoroutine
import kotlinx.coroutines.Dispatchers
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStreamReader
import java.io.OutputStreamWriter

/**笔迹草稿<颜色,该颜色的所有笔迹>*/
val drafts = mutableStateMapOf<Color, SnapshotStateList<Path>>()

/**笔迹草稿转非state结构，用于存储*/
fun drafts2draftsMap(): Map<Int, List<PathMap>>? {
    val draftMap = mutableMapOf<Int, ArrayList<PathMap>>()
    for ((color, paths) in drafts) {
        val colorInt = ColorSetData(color).id
        val pathsMap = arrayListOf<PathMap>()
        for (path in paths) {
            val pathMap = PathMap(path.penSize)
            for (oft in path.points) pathMap.points.add(PathMap.XY(x = oft.x, y = oft.y))
            if (pathMap.points.isNotEmpty()) pathsMap.add(pathMap)
        }
        if (pathsMap.isNotEmpty()) draftMap[colorInt] = pathsMap
    }
    return if (draftMap.isEmpty()) null else draftMap
}

/**非state结构转笔迹草稿，用于绘图*/
fun draftsMap2drafts(draftMap: Map<Int, List<PathMap>>) {
    drafts.clear()
    for ((colorInt, pathsMap) in draftMap) {
        val color = ColorSetData.int2color(colorInt)
        val paths = mutableStateListOf<Path>()
        for (pathMap in pathsMap) {
            val path = Path(pathMap.penSize)
            for (xy in pathMap.points) path.points.add(Offset(x = xy.x, y = xy.y))
            if (path.points.isNotEmpty()) paths.add(path)
        }
        if (paths.isNotEmpty()) drafts[color] = paths
    }
}

/**向文件保存草稿映射*/
fun draftsMap2file(file: File, draftMap: Map<Int, List<PathMap>>) {
    inCoroutine(Dispatchers.IO) {
        val json = Gson().toJson(draftMap)
        FileOutputStream(file).use {
            OutputStreamWriter(it).use { writer ->
                writer.write(json)
            }
        }
    }
}

/**从文件读取字符串*/
fun file2draftsMap(file: File): Map<Int, List<PathMap>>? {
    var str: String
    FileInputStream(file).use { fis ->
        InputStreamReader(fis).use { str = it.readText() }
    }
    return string2draftMap(str)
}

/**字符串转草稿映射
 * @return null 转换失败*/
fun string2draftMap(string: String): Map<Int, List<PathMap>>? {
    return try {
        val type = object : TypeToken<Map<Int, List<PathMap>>>() {}.type
        Gson().fromJson<Map<Int, List<PathMap>>>(string, type)
    } catch (e: Exception) {
        Log.e("string2draftMap", e.stackTraceToString())
        null
    }
}

/**一条路径
 * @param penSize 笔尺寸
 * @param points 路径点所在位置*/
data class Path(
    val penSize: Float, val points: SnapshotStateList<Offset> = mutableStateListOf()
)

/**路径映射，用于储存*/
data class PathMap(
    val penSize: Float, val points: ArrayList<XY> = arrayListOf()
) {
    data class XY(
        val x: Float, val y: Float
    )
}